require('module-alias/register');
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const app_config = require('@/config/app')
global._ = require('lodash');
global._code = require('@/config/types')

/**
 *
 * 公共系统初始化
 *
 */
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

// 设置跨域和相应数据格式
app.all('/api/*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, mytoken')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Authorization')
  res.setHeader('Content-Type', 'application/json;charset=utf-8')
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('X-Powered-By', ' 3.2.1')
  if (req.method == 'OPTIONS') res.send(200)
    /*让options请求快速返回*/ else next()
})

// 初始化统一响应机制
var resextra = require('./modules/resextra')
app.use(resextra)

app.get('/', (req, res) => {
  res.send('Hello World')
})

/**
 * 初始化路由
 */
// 带路径的用法并且可以打印出路有表
app.use('/api/v1/article', require('@/routes/api/v1/article'));
app.use('/api/v1/tag', require('@/routes/api/v1/tag'));
app.use('/api/v1/category', require('@/routes/api/v1/category'));

app.listen(app_config.port, async () => {
  console.log(`Example app listening at http://localhost:${app_config.port}`);
})

module.exports = app